package com.v3admin.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.v3admin.common.service.IServiceImpl;
import com.v3admin.system.domain.SystemRole;
import com.v3admin.system.domain.SystemUserRole;
import com.v3admin.system.mapper.SystemUserRoleMapper;
import com.v3admin.system.service.SystemRoleService;
import com.v3admin.system.service.SystemUserRoleService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 实现类
 *
 * @author Junpeng.Li
 * @date 2023-12-14 16:21
 */
@Service
@AllArgsConstructor
public class SystemUserRoleServiceImpl extends IServiceImpl<SystemUserRoleMapper, SystemUserRole>
        implements SystemUserRoleService {

    private final SystemRoleService roleService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setRole(Long userId, Set<Long> roleIds) {
        this.validateRoleIds(roleIds);

        // 1. 先清空
        this.removeByUser(userId);
        // 2. 再重新插入
        List<SystemUserRole> list = new ArrayList<>(roleIds.size());
        roleIds.forEach(roleId -> list.add(new SystemUserRole(userId, roleId)));
        super.saveBatch(list);
    }

    @Override
    public void removeByUser(Long userId) {
        QueryWrapper<SystemUserRole> wrapper = queryWrapper(wrap -> wrap.eq(SystemUserRole.TBF_USER_ID, userId));
        super.remove(wrapper);
    }

    @Override
    public void removeByRoleId(Long roleId) {
        QueryWrapper<SystemUserRole> wrapper = queryWrapper(wrap -> wrap.eq(SystemUserRole.TBF_ROLE_ID, roleId));
        super.remove(wrapper);
    }

    /**
     * 校验角色ID集合，去除不合法的ID（在角色表中不存在的ID）
     *
     * @param roleIds 角色ID集合
     */
    private void validateRoleIds(Set<Long> roleIds) {
        List<SystemRole> roles = roleService.listByIds(roleIds);
        // 合法
        if (roles.size() == roleIds.size()) {
            return;
        }

        List<Long> tempIds = roles.stream().map(SystemRole::getId).collect(Collectors.toList());
        // 将不合法的id去除
        roleIds.removeIf(roleId -> !tempIds.contains(roleId));
    }
}
